package com.credithc.signature.common.service.lanmao;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cfca.ra.cs.generated.CertApplyVO;
import com.credithc.signature.common.constant.SealConstant;
import com.credithc.signature.common.po.SealInfo;
import com.credithc.signature.common.utils.EncoderUtils;
import com.credithc.signature.common.utils.PdfGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import java.io.FileInputStream;
import java.util.List;

/**
 * 懒猫签署合同业务逻辑
 * @author zhanghanqiu181212@credithc.com
 * @Date 2019/10/17 15:06
 */
@Service
@Slf4j
public class LanmaoSignService {

    @Value("${cat.sdk.customerNo:911101135769049507A}")
    private String customerNo;

    @Value("${cat.sdk.method.keyWordMethod:/contract/sign/keywords/batch}")
    private String keyWordMethod;

    @Value("${cat.sdk.method.lockMethod:/sign/contract/lock}")
    private String lockMethod;

    @Value("${cat.sdk.method.verifyMethod:/sign/pdf/verify}")
    private String verifyMethod;

    @Autowired
    private LanmaoSdkClient lanmaoSdkClient;

    @Autowired
    private LanmaoRegisterService lanmaoRegisterService;


    /**
     * 准备私章参数
     * @param jsonArray
     * @param certApplyVOS
     * @return
     * @throws Exception
     */
    public JSONArray bulidPersonKeyWordParm(JSONArray jsonArray,List<CertApplyVO> certApplyVOS) throws Exception {


        for (CertApplyVO certApply :certApplyVOS) {
            String userId = lanmaoRegisterService.registerPerson(certApply.getUserName(), certApply.getUserIdNo(), certApply.getIdTypeCode());
            JSONObject signInfo = new JSONObject();
            signInfo.put("userId", userId);
            signInfo.put("signatureImageHeight","30");
            signInfo.put("signatureImageWidth","40");
            JSONArray keywords = new JSONArray();
            keywords.add("$_"+certApply.getUserName()+"_$");
            signInfo.put("keywords", keywords);
            signInfo.put("align", "cc");
            jsonArray.add(signInfo);
        }

        return jsonArray;

    }

    /**
     * 准备签署公章参数
     * @param jsonArray
     * @param sealInfos
     * @return
     * @throws Exception
     */

    public JSONArray bulidEntKeyWordParm(JSONArray jsonArray,List<SealInfo> sealInfos) throws Exception {
        for (SealInfo sealInfo:sealInfos) {
            String userId = lanmaoRegisterService.registerEnt(sealInfo.getSealCode());
            JSONObject signInfo = new JSONObject();
            signInfo.put("userId", userId);
            signInfo.put("signatureImageHeight","115");
            signInfo.put("signatureImageWidth","115");
            JSONArray keywords = new JSONArray();
            keywords.add(sealInfo.getKeyWords());
            signInfo.put("keywords", keywords);
            signInfo.put("align", "cc");
            jsonArray.add(signInfo);
        }

        return jsonArray;
    }

    /**
     * 关键字签署
     * @param fileId
     * @param signInfos
     * @throws Exception
     */


    public void keyWordSign(String fileId,  JSONArray signInfos ) throws Exception {
        JSONObject json = new JSONObject();
        JSONObject head = new JSONObject();
        head.put("customerNo", customerNo);
        json.put("head", head);
        JSONObject body = new JSONObject();
        body.put("contractId", fileId);
        body.put("signInfos", signInfos);
        json.put("body", body);
        JSONObject rsp = lanmaoSdkClient.post(keyWordMethod, json);
     /*   System.out.println(json.toString());
        System.out.println(rsp.toString());*/
        JSONObject rshead = rsp.getJSONObject("head");
        if (!SealConstant.SUCCESS.equals(rshead.get("rspCode"))){
            log.error("关键字签章失败{}",rsp.toJSONString());
            throw  new Exception(rshead.toString());
        }
        log.info("关键字签章成功{}",rsp.toJSONString());
    }

    /**
     * 签署完成 锁定合同
     * @param fileId
     * @throws Exception
     */

    public void contactLock(String fileId) throws Exception{
        JSONObject body = new JSONObject();
        body.put("contractId", fileId);
        JSONObject postData = new JSONObject();
        JSONObject head = new JSONObject();
        head.put("customerNo", customerNo);
        postData.put("head", head);
        postData.put("body", body);
        JSONObject response = lanmaoSdkClient.post(lockMethod, postData);
        JSONObject rshead = response.getJSONObject("head");
        if (!SealConstant.SUCCESS.equals(rshead.get("rspCode"))){
            log.info("{}锁定文档失败{}",fileId,response.toJSONString());
            throw  new Exception(rshead.toString());
        }
        log.info("{}锁定文档成功{}",fileId,response.toJSONString());
    }

    /**
     * 验证文档是否有效
     * @param filePath
     * @return
     * @throws Exception
     */
    public Boolean verifySign(String filePath,String fileId)throws Exception{
        //String method = "/sign/pdf/verify";
        JSONObject json = new JSONObject();
        JSONObject head = new JSONObject();
        head.put("customerNo", customerNo);
        json.put("head", head);
        JSONObject details = new JSONObject();
        byte[] bytes = PdfGenerator.getContent(filePath);

        details.put("file", EncoderUtils.base64EncodeToString(bytes));
      //  details.put("fileId", fileId);
        json.put("body", details);
        JSONObject rsp = lanmaoSdkClient.post(verifyMethod, json);
        JSONObject rshead = rsp.getJSONObject("head");
        if (!SealConstant.SUCCESS.equals(rshead.get("rspCode"))){
            throw  new Exception(rshead.toString());
        }
        return rsp.getJSONObject("body").getBoolean("result");
    }

}
